package com.pureut.retrospect.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.protobuf.ServiceException;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.retrospect.domain.dto.*;
import com.pureut.retrospect.mapper.MaterialAwmateriaMapper;
import com.pureut.retrospect.service.ProductTraceabilityService;
import com.pureut.system.api.QualityFeginService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: YSL
 * @Date: 2023/4/12 11:19
 * @Desc: 产品追溯
 */
@Service
public class ProductTraceabilityServiceImpl implements ProductTraceabilityService {

    /**
     * 远程调用仓库
     */
    @Resource
    private StorageFegin storageFegin;

    /**
     * 原料信息
     */
    @Resource
    private MaterialAwmateriaMapper materialAwmateriaMapper;

    /**
     * 品检信息
     */
    @Resource
    private QualityFeginService qualityFeginService;

    /**
     * 生产信息
     */
    @Resource
    private FeignProductionService feignProductionService;

    /**
     * 基础信息
     *
     * @param codingType
     * @param wsiMaterialNumber
     * @return
     */
    @Override
    public List<ProductTraceabilityDto> getProductTraceabilityList(String codingType, String wsiMaterialNumber) {

        AjaxResult list = storageFegin.getProductTraceabilityList(codingType, wsiMaterialNumber);
        List<ProductTraceabilityDto> data = JSON.parseArray(JSON.toJSONString(list.get("data")), ProductTraceabilityDto.class);
        if (ObjectUtil.isNull(data)) {
            throw  new GlobalException("物料不存在！");
        }
        for (ProductTraceabilityDto productTraceabilityDto : data) {
            // 原料详情
            MaterialFinishedDto materialFinishedInfo = materialAwmateriaMapper.getMaterialFinishedInfo(productTraceabilityDto.getWsiMaterialCode());

            GregorianCalendar calendar = new GregorianCalendar();
            if (null != materialFinishedInfo) {
                if (productTraceabilityDto.getWsiReveiveTime() != null) {
                    // 复检日期=入库时间（库存汇总）+复检日期（基础配置）
                    calendar.setTime(productTraceabilityDto.getWsiReveiveTime());
                    calendar.add(Calendar.DATE, materialFinishedInfo.getMaterialInspection());
                    Date wsiRecheckTime = calendar.getTime();
                    productTraceabilityDto.setWsiRecheckTime(wsiRecheckTime);
                }

                if (productTraceabilityDto.getWsiProducedDate() != null) {
                    // 过保日期=生产日期（库存汇总）+保质期（基础配置）
                    calendar.setTime(productTraceabilityDto.getWsiProducedDate());
                    calendar.add(Calendar.DATE, materialFinishedInfo.getMaterialQuality());
                    Date wsiExpirationTime = calendar.getTime();
                    productTraceabilityDto.setWsiExpirationTime(wsiExpirationTime);
                }
            }
            // 工艺卡编码
            AjaxResult process = feignProductionService.getProcessCardCoding(productTraceabilityDto.getWsiConnectNum());
            TraceabilitySpunlaceOrderDto data1 = JSON.parseObject(JSON.toJSONString(process.get("data")), TraceabilitySpunlaceOrderDto.class);
            if (data1 != null) {
                productTraceabilityDto.setProcessCardCoding(data1.getProcessCardCoding());
            }
        }

        return data;
    }

    /**
     * 品检信息
     *
     * @param wsiMaterialNumber
     * @return
     */
    @Override
    public List<MaterialQualityDto> getProductQualityTemporaryList(String codingType, String wsiMaterialNumber) {

        List<MaterialQualityDto> list1 = new ArrayList<>();


        // 1、当类型为成品时
        if (codingType.equals("1")) {
            // 查询成品称重
            AjaxResult ajaxResult = feignProductionService.selectWeighingFinishedMaterialProductList(wsiMaterialNumber);
            List<TraceabilityProductDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), TraceabilityProductDto.class);
            for (TraceabilityProductDto traceabilityProductDto : data) {

                AjaxResult list = qualityFeginService.getQualityTemporaryList(traceabilityProductDto.getMasterVolumeNumber());
                if (list != null) {
                    List<MaterialQualityDto> data1 = JSON.parseArray(JSON.toJSONString(list.get("data")), MaterialQualityDto.class);
                    list1.addAll(data1);
                }

                AjaxResult patrolTemporaryList = qualityFeginService.getPatrolTemporaryList(traceabilityProductDto.getMasterVolumeNumber());
                if (patrolTemporaryList != null) {
                    List<MaterialQualityDto> data2 = JSON.parseArray(JSON.toJSONString(patrolTemporaryList.get("data")), MaterialQualityDto.class);
                    list1.addAll(data2);
                }
            }
        }

        // 2、母卷
        if (codingType.equals("2")) {
            AjaxResult ajaxResult = feignProductionService.selectRollPackingHistoryMasterVolumeNumber(wsiMaterialNumber);
            List<RollPackingHistoryDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), RollPackingHistoryDto.class);
            for (RollPackingHistoryDto rollPackingHistoryDto : data) {
                // 品检
                AjaxResult list = qualityFeginService.getQualityTemporaryList(rollPackingHistoryDto.getMasterVolumeNumber());
                if (list != null) {
                    List<MaterialQualityDto> data2 = JSON.parseArray(JSON.toJSONString(list.get("data")), MaterialQualityDto.class);
                    list1.addAll(data2);
                }

                // 巡检
                AjaxResult patrolTemporaryList = qualityFeginService.getPatrolTemporaryList(rollPackingHistoryDto.getMasterVolumeNumber());
                if (patrolTemporaryList != null) {
                    List<MaterialQualityDto> data3 = JSON.parseArray(JSON.toJSONString(patrolTemporaryList.get("data")), MaterialQualityDto.class);
                    list1.addAll(data3);
                }
            }
        }

        // 3、小卷无品检

        return list1.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 同批次物料
     *
     * @param wsiMaterialNumber
     * @return
     */
    @Override
    public List<RetrospectMaterialDto> getProductSameBatchList(String codingType, String wsiMaterialNumber) {
        AjaxResult retrospectMaterialList = storageFegin.getRetrospectProductList(codingType, wsiMaterialNumber);
        return JSON.parseArray(JSON.toJSONString(retrospectMaterialList.get("data")), RetrospectMaterialDto.class);
    }

    /**
     * 产品履历
     *
     * @param codingType
     * @param wsiMaterialNumber
     * @return
     */
    @Override
    public List<MaterialResumeDto> getProductPersonalDetails(String codingType, String wsiMaterialNumber) {
        AjaxResult productPersonalDetails = storageFegin.getProductPersonalDetails(codingType, wsiMaterialNumber);
        List<MaterialResumeDto> data = JSON.parseArray(JSON.toJSONString(productPersonalDetails.get("data")), MaterialResumeDto.class);

//        // 作业类型
//        List<SysDictData> jobTypeGrade = DictUtils.getDictCache("job_type");
//        Map<String, String> jobTypeGradeMap = jobTypeGrade.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
//        if (data != null) {
//            for (MaterialResumeDto materialResumeDto : data) {
//                // 作业类型
//                materialResumeDto.setJobTypeDict(jobTypeGradeMap.get(materialResumeDto.getJobType()));
//            }
//        }
        return data;
    }

    /**
     * 追溯信息
     *
     * @param codingType
     * @param wsiMaterialNumber
     * @return
     */
    @Override
    public List<TraceabilityInformationDto> getTraceabilityInformationList(String codingType, String wsiMaterialNumber) {

        List<TraceabilityInformationDto> list = new ArrayList<>();
//        // 如果类型是小卷
//        if (codingType.equals("3")) {
//            // 查询小卷关联的母卷
//            AjaxResult ajaxResult = feignProductionService.getTraceabilityRollInfo(wsiMaterialNumber);
//            TraceabilityRollPackingDto data = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")), TraceabilityRollPackingDto.class);
//            if (data != null) {
//
//                AjaxResult ajaxResultList = feignProductionService.selectMasterVolumeNumberList(data.getMasterVolumeNumber());
//                List<TraceabilityRollPackingDto> dataList = JSON.parseArray(JSON.toJSONString(ajaxResultList.get("data")), TraceabilityRollPackingDto.class);
//                for (TraceabilityRollPackingDto traceabilityRollPackingDto : dataList) {
//
//                    TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();
//                    // 包装内的小卷号码
//                    traceabilityInformationDto.setAssociateSmallVolumes(traceabilityRollPackingDto.getSmallVolumeNumber());
//                    // 小卷关联的分切单号
//                    traceabilityInformationDto.setSplittingOrder(traceabilityRollPackingDto.getSplittingOrderNumber());
//                    // 小卷关联的母卷号码
//                    traceabilityInformationDto.setAssociatedParentVolume(traceabilityRollPackingDto.getMasterVolumeNumber());
//
//                    AjaxResult ajaxResult1 = storageFegin.selectProductStockInfoById(traceabilityRollPackingDto.getMasterVolumeNumber());
//                    RetrospectManageDto data2 = JSON.parseObject(JSON.toJSONString(ajaxResult1.get("data")), RetrospectManageDto.class);
//
//                    if (data2 != null) {
//                        // 查询母卷关联的水刺制令单
//                        AjaxResult processCardCoding = feignProductionService.getProcessCardCoding(data2.getWsiConnectNum());
//                        TraceabilitySpunlaceOrderDto data1 = JSON.parseObject(JSON.toJSONString(processCardCoding.get("data")), TraceabilitySpunlaceOrderDto.class);
//
//                        if (data1 != null) {
//                            // 水刺制令单号
//                            traceabilityInformationDto.setWaterStingMakingOrder(data1.getSpunlaceOrderNumber());
//                        }
//                    }
//                    list.add(traceabilityInformationDto);
//                }
//            }
//
//        }


        // 如果类型是小卷
        if (codingType.equals("3")) {
            AjaxResult ajaxResult = feignProductionService.selectRollPackingHistoryInfo(wsiMaterialNumber);
            RollPackingHistoryDto data = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")), RollPackingHistoryDto.class);
            if (data != null) {
                TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();

                AjaxResult ajaxResult1 = feignProductionService.selectSpunlaceDetailList(data.getMasterVolumeNumber());
                SpunlaceOutputDetailDto data1 = JSON.parseObject(JSON.toJSONString(ajaxResult1.get("data")), SpunlaceOutputDetailDto.class);
                if (data1 != null) {
                    // 包装内的母卷号码
                    traceabilityInformationDto.setAssociatedParentVolume(data.getMasterVolumeNumber());
                    // 包装内的水刺制令单
                    traceabilityInformationDto.setWaterStingMakingOrder(data1.getSpunlaceOrderNumber());
                    list.add(traceabilityInformationDto);
                }
            }
        }


        // 如果类型是母卷
        if (codingType.equals("2")) {

            AjaxResult ajaxResult = feignProductionService.selectRollPackingHistoryMasterVolumeNumber(wsiMaterialNumber);
            List<RollPackingHistoryDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), RollPackingHistoryDto.class);
            for (RollPackingHistoryDto rollPackingHistoryDto : data) {
                TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();
                traceabilityInformationDto.setAssociateSmallVolumes(rollPackingHistoryDto.getSmallVolumeNumber());
                traceabilityInformationDto.setSplittingOrder(rollPackingHistoryDto.getSplittingOrderNumber());
                list.add(traceabilityInformationDto);
            }


//            AjaxResult ajaxResult = feignProductionService.selectWeighingFinishedMaterialProductList(wsiMaterialNumber);
//            List<TraceabilityProductDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), TraceabilityProductDto.class);
//            for (TraceabilityProductDto traceabilityProductDto : data) {
//                TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();
//                // 查询母卷信息
//                AjaxResult ajaxResult1 = storageFegin.selectProductStockInfoById(wsiMaterialNumber);
//                RetrospectManageDto data2 = JSON.parseObject(JSON.toJSONString(ajaxResult1.get("data")), RetrospectManageDto.class);
//                if (data2 != null) {
//                    // 查询母卷关联的水刺制令单
//                    AjaxResult processCardCoding = feignProductionService.getProcessCardCoding(data2.getWsiConnectNum());
//                    TraceabilitySpunlaceOrderDto data1 = JSON.parseObject(JSON.toJSONString(processCardCoding.get("data")), TraceabilitySpunlaceOrderDto.class);
//                    if (data1 != null) {
//                        // 水刺制令单号
//                        traceabilityInformationDto.setWaterStingMakingOrder(data1.getSpunlaceOrderNumber());
//                    }
//                }
//
//                // 小卷关联的母卷号码
//                traceabilityInformationDto.setAssociatedParentVolume(traceabilityProductDto.getMasterVolumeNumber());
//                // 小卷关联的分切单号
//                traceabilityInformationDto.setSplittingOrder(traceabilityProductDto.getSplittingOrderNumber());
//                // 包装内的小卷号码
//                traceabilityInformationDto.setAssociateSmallVolumes(traceabilityProductDto.getSmallVolumeNumber());
//
//
//                list.add(traceabilityInformationDto);
//            }

        }


        // 如果类型是成品
        if (codingType.equals("1")) {


            // 查询成品称重
            AjaxResult ajaxResult = feignProductionService.selectWeighingFinishedMaterialProductList(wsiMaterialNumber);
            List<TraceabilityProductDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), TraceabilityProductDto.class);
            for (TraceabilityProductDto traceabilityProductDto : data) {

                TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();
                AjaxResult ajaxResult1 = feignProductionService.selectSpunlaceDetailList(traceabilityProductDto.getMasterVolumeNumber());
                SpunlaceOutputDetailDto data1 = JSON.parseObject(JSON.toJSONString(ajaxResult1.get("data")), SpunlaceOutputDetailDto.class);

                // 小卷号码
                traceabilityInformationDto.setAssociateSmallVolumes(traceabilityProductDto.getSmallVolumeNumber());
                // 分切制令单
                traceabilityInformationDto.setSplittingOrder(traceabilityProductDto.getSplittingOrderNumber());
                // 母卷号码
                traceabilityInformationDto.setAssociatedParentVolume(traceabilityProductDto.getMasterVolumeNumber());
                // 水刺制令单
                traceabilityInformationDto.setWaterStingMakingOrder(data1.getSpunlaceOrderNumber());
                list.add(traceabilityInformationDto);
            }


//            List<TraceabilityInformationDto> list1 = new ArrayList<>();
//            TraceabilityInformationDto traceabilityInformationDto = new TraceabilityInformationDto();
//            AjaxResult ajaxResult1 = storageFegin.selectProductStockInfoById(wsiMaterialNumber);
//            RetrospectManageDto data2 = JSON.parseObject(JSON.toJSONString(ajaxResult1.get("data")), RetrospectManageDto.class);
//            if (data2 != null) {
//                traceabilityInformationDto.setAssociatedParentVolume(data2.getWsiMaterialNumber());
//                // 查询母卷关联的水刺制令单
//                AjaxResult processCardCoding = feignProductionService.getProcessCardCoding(data2.getWsiConnectNum());
//                TraceabilitySpunlaceOrderDto data1 = JSON.parseObject(JSON.toJSONString(processCardCoding.get("data")), TraceabilitySpunlaceOrderDto.class);
//                if (data1 != null) {
//                    // 水刺制令单号
//                    traceabilityInformationDto.setWaterStingMakingOrder(data1.getSpunlaceOrderNumber());
//                }
//                list1.add(traceabilityInformationDto);
//            }
//
//            // 查询小卷关联的母卷
//            AjaxResult ajaxResult = feignProductionService.selectMasterVolumeNumberList(wsiMaterialNumber);
//            List<TraceabilityRollPackingDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), TraceabilityRollPackingDto.class);
//            for (TraceabilityRollPackingDto traceabilityRollPackingDto : data) {
//
//                // 查询小卷关联的母卷
//                AjaxResult ajaxResultTraceability = feignProductionService.getTraceabilityRollInfo(traceabilityRollPackingDto.getSmallVolumeNumber());
//                TraceabilityRollPackingDto traceabilityData = JSON.parseObject(JSON.toJSONString(ajaxResultTraceability.get("data")), TraceabilityRollPackingDto.class);
//                if (traceabilityData != null) {
//                    // 小卷关联的母卷号码
//                    traceabilityInformationDto.setAssociatedParentVolume(traceabilityData.getMasterVolumeNumber());
//                    // 小卷关联的分切单号
//                    traceabilityInformationDto.setSplittingOrder(traceabilityData.getSplittingOrderNumber());
//                    // 包装内的小卷号码
//                    traceabilityInformationDto.setAssociateSmallVolumes(traceabilityData.getSmallVolumeNumber());
//                }
//                list1.add(traceabilityInformationDto);
//            }

//            list.addAll(list1);
        }


        return list.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 根据小卷查询小卷信息
     *
     * @param materialNumber
     * @return
     */
    @Override
    public TraceabilityRollPackingDto getTraceabilityRollInfo(String materialNumber) {
        AjaxResult traceabilityRollInfo = feignProductionService.getTraceabilityRollInfo(materialNumber);
        return JSON.parseObject(JSON.toJSONString(traceabilityRollInfo.get("data")), TraceabilityRollPackingDto.class);
    }


}
